﻿using System;
using System.Net;
using System.Text;
using Newtonsoft.Json;
using DGM.Objects.Media;
using System.ComponentModel;
using System.IO;
using System.Drawing;

namespace DGM.Util.Helpers.MediaRatingApis.RottenTomatoes
{
    public class DRTApiHelper
    {
        public DMediaRTMovie result { get; set; }
        public Image detailedPoster { get; set; }
        private string webstreamResult { get; set; }
        private string title { get; set; }

        public delegate void DownloadCompletedHandler(object sender);
        public event DownloadCompletedHandler DownloadCompleted;

        BackgroundWorker bw = new BackgroundWorker();

        public DRTApiHelper()
        {
            bw.WorkerSupportsCancellation = true;
            bw.WorkerReportsProgress = false;
            bw.DoWork += new DoWorkEventHandler(bw_DoWork);
            bw.RunWorkerCompleted += bw_RunWorkerCompleted;
        }

        public void GetMovieInfo(string title)
        {
            this.title = title;
            bw.RunWorkerAsync();
        }

        private void bw_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker = sender as BackgroundWorker;

            string formattedTitle = title.Replace(' ', '+');
            formattedTitle.Trim();
            string url = string.Format("http://api.rottentomatoes.com/api/public/v1.0/movies.json?apikey=uewtqn6ya88dr73rbufg4xmh&q={0}&page_limit=1", formattedTitle);

            using (var webClient = new WebClient())
            {
                webClient.Encoding = Encoding.UTF8;
                string webstreamResult = webClient.DownloadString(url);

                RTMoviesList list = JsonConvert.DeserializeObject<RTMoviesList>(webstreamResult);
                if (list.movies.Count > 0)
                {
                    result = list.movies[0];

                    byte[] imageDataResult = webClient.DownloadData(result.posters.detailed);
                    MemoryStream ms = new MemoryStream(imageDataResult);
                    detailedPoster = Image.FromStream(ms);
                }
            }
        }

        private void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if ((e.Cancelled == true))
            {

            }
            else if (!(e.Error == null))
            {

            }
            else
            {
                DownloadCompleted(this);
            }
        }
    }
}
